#!/bin/bash


dir=$PWD
# 监控容器列表文件
MONITOR_FILE="$dir/monitored_containers.txt"

echo "" > $MONITOR_FILE #清空数据
docker ps -a --format "{{.Names}}" | grep "znsx-" >> $MONITOR_FILE
docker ps -a --format "{{.Names}}" | grep "support-" >> $MONITOR_FILE
docker ps -a --format "{{.Names}}" | grep "darma" >> $MONITOR_FILE
echo "python3.6" >> $MONITOR_FILE
echo "webssh" >> $MONITOR_FILE
echo "portainer" >> $MONITOR_FILE

# 检查文件是否存在
if [ ! -f "$MONITOR_FILE" ]; then
	exit 0
fi
# 读取文件中的容器名
while read -r container; do
	# 跳过空行
	if [ -z "$container" ]; then
		continue
	fi
	# 检查容器状态
	status=$(docker inspect -f '{{.State.Status}}' "$container" 2>/dev/null)
	# 如果容器不存在，跳过
	if [ $? -ne 0 ]; then
		echo "Container $container not found. Removing from monitor list."
		sed -i "/^${container}$/d" "$MONITOR_FILE"
		continue
	fi
	# 如果容器状态是exited，则重启
	if [ "$status" = "exited" ]; then
	# if [ "$status" != "running" ]; then
		echo "Container $container is exited. Restarting..."
		docker restart "$container"
	fi
done < "$MONITOR_FILE"


